package com.hmall.search.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;


/**
 * ES 搜索工具类，封装了构造ES客户端、查询条件、高亮设置等工具方法
 * @author xiaopeng
 * @version 1.0
 */
@Slf4j
public class EsSearchUtils {

    /**
     * 创建RestHighLevelClient客户端
     *
     * @return RestHighLevelClient 客户端实例
     */
    public static RestHighLevelClient createClient(String httpHostStr) {
        if (httpHostStr == null || httpHostStr.trim().isEmpty()) {
            throw new IllegalArgumentException("Es httpHostStr cannot be null or empty");
        }

        try {
            return new RestHighLevelClient(RestClient.builder(HttpHost.create(httpHostStr)));
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException("Es Invalid httpHostStr format: " + httpHostStr, e);
        }
    }

    /**
     * 关闭RestHighLevelClient客户端
     * @param client
     * @return
     */
    public static boolean closeClient(RestHighLevelClient client) {
        if (client != null) {
            try {
                client.close();
                return true;
            } catch (Exception e) {
                log.error("Failed to close client", e);
                e.printStackTrace();
            }
        }
        return false;
    }



    /**
     * 计算总页数
     *
     * @param totalHits 总命中数
     * @param pageSize  每页显示数量
     * @return long 总页数
     */
    public static long calculateTotalPages(long totalHits, int pageSize) {
        return totalHits % pageSize == 0 ? totalHits / pageSize : totalHits / pageSize + 1; // 向上取整
    }


}